package com.pospi.xstore.ui.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.caigou.CgDetailActivity;
import com.pospi.xstore.ui.caigou.CgddBeen;
import com.pospi.xstore.ui.caigou.CgshListActivity;
import com.pospi.xstore.util.Api;
import com.yinglan.keyboard.HideUtil;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BaseActivity extends SuperBaseActivity {
    private TextView mTitle;
    private ImageView mBack;
    private TextView menu;
    private FrameLayout container;
    private static List<Activity> activities = new ArrayList<>();


    public static final int RE_SUCESS = 1;//请求成功
    public static final int RE_FAILED = 2;  //返回异常
    public static final int RE_NET_FAILED = 5;  //服务器接口无法访问
    public static final int RE_NOPARSING = 3; //数据无法解析
    public static final int RE_LOADMORE = 4;//加载更多成功

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        mTitle = (TextView) findViewById(R.id.title);
        mBack = (ImageView) findViewById(R.id.back);
        menu = (TextView) findViewById(R.id.menu);
        container = (FrameLayout) findViewById(R.id.container);
        activities.add(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        activities.remove(this);
    }

    public static void killBaseActivity() {
        for (Activity activity : activities) {
            activity.finish();
        }
    }

    /***
     * 设置内容区域
     *
     * @param resId 资源文件ID
     */
    @SuppressWarnings("deprecation")
    public void setContentLayout(int resId) {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(resId, null);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT);
        contentView.setLayoutParams(layoutParams);
        contentView.setBackgroundDrawable(null);
        if (null != container) {
            container.addView(contentView);
        }
    }

    /**
     * 设置中间title的文字
     */
    public void setTitle(String title) {
        mTitle.setText(title);
    }

    /**
     * 设置中间title的文字
     */
    public void setTitle(int title) {
        mTitle.setText(title);
    }

    /**
     * 设置右边按钮的文字
     */
    public void setMenuText(String text) {
        menu.setVisibility(View.VISIBLE);
        menu.setText(text);
    }

    /**
     * 设置右边按钮的图片资源
     */
    public void setMenuImage(int resId) {
        if (null != menu) {
            menu.setVisibility(View.VISIBLE);
            menu.setBackgroundResource(resId);
        }
    }

    public TextView getMenu() {
        return menu;
    }

    /**
     * 设置左边后退按钮的隐藏与显示
     */
    public void setBackVisible(boolean visible) {
        if (visible) {
            mBack.setVisibility(View.VISIBLE);
        } else {
            mBack.setVisibility(View.GONE);
        }
    }

    /**
     * 设置右边按钮的点击事件
     */
    public void onMenuClick(View view) {

    }

    /**
     * 设置左边后退按钮的点击事件
     */
    public void onBack(View view) {
        onBackPressed();
    }

    /**
     * 打开一个Activity
     */
    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    public DialogFragment mDialogFragment;

    public void showMyDialog(String msg) {
        mDialogFragment = new CircleDialog.Builder()
                .setProgressText(msg)
                .setProgressStyle(ProgressParams.STYLE_SPINNER)
                .show(getSupportFragmentManager());
    }

    public void closeMyDialog() {
        mDialogFragment.dismiss();
    }

    public static boolean NumberCheck(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    private DialogFragment dialog;

    public void showDialog() {
        dialog = new CircleDialog.Builder()
                .setProgressText("加载中...")
                .setProgressStyle(ProgressParams.STYLE_SPINNER)
                .show(getSupportFragmentManager());
    }

    public void close() {
        dialog.dismiss();
    }


    public void requestNet(RequestParams params , final Handler handler){
        showDialog();
        Log.i("requestNet",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                close();
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    String errCode = jsonObject.getString("errCode");
                    String errMsg = jsonObject.getString("errMsg");
                    if (errCode.equals("100")) {
                        Message message = Message.obtain();
                        message.what = RE_SUCESS;
                        message.obj = new String(bytes);
                        handler.sendMessage(message);
                    } else {
                        printFailedMsg(errMsg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    printFailedMsg("解析异常");
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                close();
                printFailedMsg("服务器请求失败");
            }
        });
    }
    private void printFailedMsg(final String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new CircleDialog.Builder()
                        .setTitle("提示")
                        .setText(msg)
                        .setPositive("确定", null)
                        .show(getSupportFragmentManager());

            }
        });
    }
    private void printSucess(final String msg , final Class aClass, final Activity activity){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new CircleDialog.Builder()
                        .setTitle("提示")
                        .setText(msg)
                        .setPositive("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(aClass);
                                activity.finish();
                            }
                        })
                        .show(getSupportFragmentManager());

            }
        });
    }
    //审核统一接口
    public void requestAudit(RequestParams params , final Class aClass, final Activity activity){
        showDialog();
        Log.i("requestNet",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                close();
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    String errCode = jsonObject.getString("errCode");
                    String errMsg = jsonObject.getString("errMsg");
                    if (errCode.equals("100")) {
                        printSucess(errMsg, aClass, activity);
                    } else {
                        printFailedMsg(errMsg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    printFailedMsg("解析异常");
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                close();
                printFailedMsg("服务器请求失败");
            }
        });
    }
}